/**
 * Created by tdzl2_000 on 2016-01-25.
 */
import React, { PropTypes } from 'react';
import {
  View,
} from 'react-native';
import { match } from 'react-router';

export default class RouterContainer extends React.Component {
  static propTypes = {
    route: PropTypes.object,
    location: PropTypes.string,
    passProps: PropTypes.object,
    routeConfig: PropTypes.object,
  };

  static childContextTypes = {
    location: PropTypes.string,
  };

  state = {};

  componentWillMount() {
    this.doMatch();
  }
  componentWillReceiveProps() {
    this.doMatch();
  }

  getChildContext() {
    return {
      location: this.props.location,
    };
  }

  doMatch() {
    const { location, routeConfig } = this.props;

    if (__DEV__) {
      console.log('Current location:', location);
    }
    match({
      location,
      routes: routeConfig,
    }, (err, redirectLocation, renderProps) => {
      if (err) {
        console.error(err.stack);
      } else {
        this.setState({ routerState: renderProps });
      }
    });
  }
  render() {
    const { passProps, route } = this.props;
    const { routerState } = this.state;
    if (routerState) {
      const {
        routes,
        params,
      } = routerState;
      return routes.reduceRight((children, config) => {
        const Component = config.component;
        return Component ? (
          <Component
            route={route}
            {...passProps}
            params={params}
          >
            {children}
          </Component>
        ) : children;
      }, null);
    }
    return <View />;
  }
}
